var exec = require('child_process').exec
var request = require("request");
var fs = require('fs');
var config = require("../conf")


const  filePath  = '/file/overseas/'

/* 目录初始化 */
export function fileInit(){

    const baseFilePath = "." + filePath

    fs.exists(baseFilePath,(isExist) =>{
        
        if(!isExist){

            // 如果不存在目录 则创建
            fs.mkdir(baseFilePath,(err) =>{

                if(err){
                    throw new Error(err)
                }

            })

        }

    })
}


/* 调用shell脚本 同步file目录到cdn */
export function syncToCdn () {
    return new Promise((resolve, reject) => {
        let childProcess = exec(config.shellPath, function (err, stdout, stderr) {
            if (err) {
                reject(err)
            }
            childProcess.kill()
            resolve(stdout, stderr)
        });

    })
}

/* 由于google图片在国内无法访问，下载图片到file/overseas目录 */
export function getIcon (appId, iconUrL) {
    return new Promise((resolve, reject) => {
        let saveUrl = filePath + appId + ".jpg"
        let stream = fs.createWriteStream("." + saveUrl, { autoClose: true })
        let option = {
            url: iconUrL + "=s64", // 取icon小图
            timeout: 5000,
        }
        if (config.proxy) {
            option["proxy"] = config.proxy
        }
        request.get(option, function (err) {
            if (err) {
                stream.close()
                reject(err)
            }
        }).pipe(stream)
            .on('error', e => {
                stream.close()
                reject(e)
            })
            .on('finish', () => {
                stream.close()
                let cdnUrl = config.cdn + saveUrl
                resolve(cdnUrl)
            })
            .on('close', () => {
                stream.close()
                reject()
            })
    })

}

/* 睡眠 */
export function sleep (timeout) {
    return new Promise(resolve => setTimeout(resolve, timeout))
}

/* 报警 */
export function sendWarning (emailMsg) {

    if(config.testMode){
        console.log("测试模式。不发送报警");
        return
    }
    const params = {
        typeMsg: "ASO海外服务器 Google Play异常报警",
        emailTitle: "Google Play ASO异常报警",
        emailMsg: "【Google Play】：" + emailMsg,
        otherMsg: "",
        sendTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
        partyId: config.warnConfig.partyId,

    }
    request.post({
        url: config.warnConfig.url,
        headers: {
            "content-type": "application/x-www-form-urlencoded"
        },
        form: params
    }, function (err, resp, body) {
        if (!err && resp.statusCode == 200) {
            try {
                const res = JSON.parse(body)
                if (res.code != 1) {
                    console.log("报警发送失败！！！，res=",res);
                } else {
                    console.log("报警发送成功！！！");
                }
            } catch (error) {
                console.log("报警发送失败！！！，body=",body,error);
            }

        }
    })
}
